<template>
  <div>

    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="100px">

      <el-row :gutter="20">

        <el-col :span="15">
          <h3>基本信息</h3>
          <el-card>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="题库名称" prop="title">
                  <el-input v-model="postForm.title" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="题库分类">
                  <dic-catalog-tree v-model="postForm.catId" dic-code="repo_catalog" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="题库描述" prop="remark">
                  <el-input v-model="postForm.remark" type="textarea" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="作用范围">
                  <el-checkbox v-model="postForm.isExam" label="用于考试" />
                  <el-checkbox v-model="postForm.isTrain" label="用于训练" />
                </el-form-item>
              </el-col>

            </el-row>

          </el-card>

          <div v-if="postForm.isTrain">

            <h3>
              训练权限
            </h3>

            <el-card>

              <el-radio-group v-model="postForm.openType" size="small">
                <el-radio :label="1">完全公开</el-radio>
                <el-radio :label="2">部门开放</el-radio>
                <el-radio :label="3">指定人员</el-radio>
              </el-radio-group>

              <div style="padding-top: 20px">

                <div v-if="postForm.openType==1">
                  <el-alert
                    title="开放的，任何人都可以进行训练！"
                    type="warning"
                  />
                </div>

                <div v-if="postForm.openType==2">
                  <depart-refs v-model="postForm.deptCodes" />
                </div>

                <div v-if="postForm.openType==3">
                  <user-refs
                    :ref-id="postForm.id || tempId"
                    list-url="/api/repo/person/paging"
                    join-url="/api/repo/person/join"
                    remove-url="/api/repo/person/remove"
                  />

                </div>

              </div>

            </el-card>

          </div>

          <div style="margin-top: 20px">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button type="info" @click="onCancel">返回</el-button>
          </div>

        </el-col>

        <el-col :span="9">

          <el-row>

            <el-col>
              <h3 style="display: inline-block">章节管理</h3>
              <el-button type="primary" icon="el-icon-plus" size="small" style="float: right; margin-block-start: 1em;margin-block-end: 1em;" @click="addChapter">添加</el-button>
            </el-col>
            <el-col>

              <el-card style=" overflow-y: auto">

                <el-table
                  :data="postForm.chapters"
                  height="calc(100vh - 260px)"
                  row-key="id"
                >

                  <el-table-column
                    prop="title"
                    label="章节名称"
                  >

                    <template v-slot="scope">
                      <el-input v-model="scope.row.title" />
                    </template>

                  </el-table-column>

                  <el-table-column
                    prop="quCount"
                    align="center"
                    label="试题数量"
                    width="100px"
                  />

                  <el-table-column
                    label="操作"
                    width="120px"
                    align="center"
                  >

                    <template v-slot="scope">
                      <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeChapter(scope.$index, scope.row.quCount)" />
                      <el-button size="mini" icon="el-icon-rank" circle />
                    </template>

                  </el-table-column>

                </el-table>

              </el-card>

            </el-col>
          </el-row>

        </el-col>
      </el-row>

    </el-form>

  </div>
</template>

<script>

import Sortable from 'sortablejs'

import { fetchDetail, saveData } from '@/api/repo/repo'
import DicCatalogTree from '@/components/DicTreeSelect'
import DepartRefs from '@/components/DepartRefs'
import UserRefs from '@/components/UserRefs'
import { uuid } from 'vue-uuid'
import ToolTip from '@/components/ToolTip'
import { mapGetters } from 'vuex'

export default {
  name: 'QuRepoDetail',
  components: {
    ToolTip,
    UserRefs,
    DepartRefs,
    DicCatalogTree
  },
  data() {
    return {

      tempId: `temp_${uuid.v4()}`,

      postForm: {
        catId: '',
        chapters: [],
        isExam: true,
        isTrain: true,
        openType: 1,
        price: 0
      },
      loading: false,
      rules: {

        title: [
          { required: true, message: '题库名称不能为空！' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },
  mounted() {
    // 拖动表格
    const table = document.querySelector('.el-table__body-wrapper tbody')
    const that = this
    Sortable.create(table, {
      onEnd({ newIndex, oldIndex }) {
        console.log(newIndex, oldIndex)
        const targetRow = that.postForm.chapters.splice(oldIndex, 1)[0]
        that.postForm.chapters.splice(newIndex, 0, targetRow)
      }
    })
  },
  created() {
    const id = this.$route.params.id
    if (id !== undefined) {
      this.fetchData(id)
    }
  },
  methods: {

    // 添加子项
    handleAdd() {
      this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
    },

    fetchData(id) {
      const params = { id: id }
      fetchDetail(params).then(response => {
        this.postForm = response.data
      })
    },

    submitForm() {
      // 赋值临时
      if (!this.postForm.id) {
        this.postForm.id = this.tempId
      }

      console.log(JSON.stringify(this.postForm))

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }

        saveData(this.postForm).then(() => {
          this.$notify({
            title: '成功',
            message: '题库保存成功！',
            type: 'success',
            duration: 2000
          })

          this.$router.push({ name: 'ListRepo' })
        })
      })
    },

    onCancel() {
      this.$router.push({ name: 'ListRepo' })
    },

    addChapter() {
      this.postForm.chapters.push({ title: '新章节' })
    },

    removeChapter(index, quCount) {
      if (quCount > 0) {
        // 删除
        this.$confirm('此前挂靠在此章节下试题章节属性将被置空，确认要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.postForm.chapters.splice(index, 1)
        })
      } else {
        this.postForm.chapters.splice(index, 1)
      }
    }

  }
}
</script>
